const { app, BrowserWindow } = require('electron')
const path = require('path')
const { checkForUpdates } = require('./autoupdate');
const { spawn } = require('child_process')
const fse = require('fs-extra')
const fs = require('fs')

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            devTools: true,
            nodeIntegration: true
        }
    })

    mainWindow.loadFile('index.html')
}

app.whenReady().then(() => {
    createWindow()

    app.on('activate', function () {
        if (BrowserWindow.getAllWindows().length === 0) createWindow()
    })
});

app.on('window-all-closed', function () {
    if (process.platform !== 'darwin') app.quit()
})

app.on('ready', function () {
    checkForUpdates(app);
})

app.on('quit', () => {
    console.log('quit')
    const resourcesPath = process.resourcesPath
    if (fse.pathExistsSync(path.join(app.getPath('userData'), './')) && fse.pathExistsSync(path.join(resourcesPath, './update.asar'))) {
        const logPath = app.getPath('logs')
        const out = fs.openSync(path.join(logPath, './out.log'), 'a')
        const err = fs.openSync(path.join(logPath, './err.log'), 'a')
        const child = spawn(`"${path.join(app.getPath('userData'), './update.exe')}"`, [`"${resourcesPath}"`, `"${app.getPath('exe')}"`], {
            detached: true,
            shell: true,
            stdio: ['ignore', out, err]
        })
        child.unref()
    }
})